package com.bakend.modules.chat;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class NettyMsgAdapter extends SimpleChannelInboundHandler<Object> {
    private final static Logger netError = LogManager.getLogger("NETLOGERRORLOG");

    private final static Logger infoLog = LogManager.getLogger(NettyMsgAdapter.class);

    /**
     * 数据读取端口
     *
     * @param chc
     * @param i
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext chc, Object i) throws Exception {
        ByteBuf b = (ByteBuf) i;
        int mseLen = b.readableBytes();
        if (mseLen < 1) {
            return;
        }
        ByteBuffer buf = ByteBuffer.allocate(mseLen);
        buf.order(ByteOrder.LITTLE_ENDIAN);
        b.readBytes(buf);
        //TODO 消息处理
    }

    /**
     * 网络连接异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        netError.info(ctx, cause);
    }

    /**
     * 首次连接
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

    }

    /**
     * 连接注销， 主动与被动都会激活
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
    }
}
